using System;
using System.Threading.Tasks;

namespace Cz
{
    public class CzTask : ICzTask
    {
        [CzServiceField] private ICzLog log;
        
        private TaskFactory taskFactory;
        
        public void Start()
        {
            taskFactory = new TaskFactory();
            log.Info("CzTask Start");
        }

        public Task CreateTask(Action action, TaskCreationOptions options = TaskCreationOptions.None)
        {
            var ret = taskFactory.StartNew(action, options);
            CatchTaskException(ret);
            return ret;
        }

        public Task<T> CreateTask<T>(Func<T> action, TaskCreationOptions options = TaskCreationOptions.None)
        {
            var ret = taskFactory.StartNew(action, options);
            CatchTaskException(ret);
            return ret;
        }

        private void CatchTaskException(Task task)
        {
            task.ContinueWith(t =>
            {
                log.Error("CzTask task error", null, t.Exception);
            }, TaskContinuationOptions.OnlyOnFaulted);
        }
    }
}